package com.suny.juc;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 阻塞所有线程  当最后一个线程到达后先运行指定任务, 在运行其他线程
 * @author sunny
 * @date 2019/3/5
 */
public class CyclicBarrierTest {

    private static CyclicBarrier barrier;
    private static class CyclicBarrierThread extends Thread {


        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " 到了!!");

            try {
                //使当前线程在锁存器倒计数至零之前一直等待，除非线程被中断
                barrier.await();
                for (int i = 0; i < 10; i++) {
                    System.out.println(Thread.currentThread().getName());
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        barrier = new CyclicBarrier(5, () -> System.out.println("开始吧!!!"));

        for (int i = 0; i < 5; i++) {
            new CyclicBarrierThread().start();
        }
    }
}
